/**
* @file response_storage_image.cpp
*
*	 Nel file response_storage_image.cpp viene implementata la classe 
*	 Response_Storage_Image
*	
* @author Favale Angelo
* @author Fagioli Alessio
*
* @version 1.0
*/

#include "response_storage_image.h"

Response_Storage_Image::Response_Storage_Image(host peer){

	strcpy(this->name, "Storage_Image");
	strcpy(this->entita.ip,peer.ip);
	this->entita.porta=peer.porta;
	this->entita.s=peer.s;


}


bool Response_Storage_Image::decode_request(char buf[], char nome_file[], char lunghezza_file[]){

	unsigned int i=0,c;
	
	memset(nome_file,0,BUFFER_SIZE);
	memset(lunghezza_file,0,BUFFER_SIZE);

	while(buf[i]!=';' && i<BUFFER_SIZE)
	{
		nome_file[i]=buf[i];
		i++;
	}

	if(i==BUFFER_SIZE)
		return false;
	i++;
	c=i;

	while(buf[i]!='#' && i < BUFFER_SIZE)
	{
		lunghezza_file[i-c]=buf[i];
		i++;
	}
	
	if(i==BUFFER_SIZE)
		return false;

	return true;

}


bool Response_Storage_Image::code_request(char * file){

	int i,n;
	char buf[BUFFER_SIZE],nome_file[BUFFER_SIZE];

	memset (nome_file,0,BUFFER_SIZE);
	
	i=0;

	n=get_len_image(file);

	
	while(file[i++]!='/');
	strcpy(nome_file,&file[i]);

		
	sprintf(buf,"%s;%s;%d#",this->name,nome_file,n);

	if (send(entita.s,buf,strlen(buf),0)==-1)
		{		
		printf("Errore invio\n");
		return false;
		}

	return true;
}


bool Response_Storage_Image::send_image (char * nome_file){

	FILE *fp;
	int n,i;
	char msg[BUFFER_SIZE];
	
	i=0;

	if(!(fp=fopen(nome_file,"rb")))
		return false;

	do
	{
	 	n=fread(msg,1,512,fp);
		if(send(entita.s,msg,n,0)==-1)
			{		
			printf("Errore invio\n");
			return false;
			}
		i+=n;
	}while(n>0);

	fclose (fp);
	
	return true;

}	


void Response_Storage_Image::code_response(bool verify)
{
	
	char msg[BUFFER_SIZE];
	memset(msg,0,BUFFER_SIZE);
	
	if (verify)
		strcpy(msg,"1;");
	else
		strcpy(msg,"0;");
		
	send(entita.s,msg,strlen(msg),0);
		
	
}


bool Response_Storage_Image::decode_response()
{
	
	char msg[BUFFER_SIZE];	

	memset (msg,0,BUFFER_SIZE);

	recv(entita.s,msg,sizeof(msg),0);
	
	if (msg[0]=='1')
		//richiesta effettuata correttamente
		return true;
	else
		//errore nella codifica della richiesta
	    	return false;


}
///////////////////////////////////////////////////////////


